package loader

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
)

var (
	httpSrvs []*http.Server
	port     = 80
)

//AutoService 使用默认的配置启动程序
func AutoService() {
	if err := Service(); err != nil {
		log.Panic(err)
	}

	lend := make(chan bool)
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	go func() {
		for range c {
			log.Println("received ctrl+c,wait back job finished...")
			// core.TaskWaitGroup.Wait() //这个等待是为了任务执行这里暂时用不着
			log.Println("all back job finished,now shutdown http server...")
			Shutdown()
			log.Println("success shutdown")
			lend <- true
			break
		}
	}()
	//blockforever
	<-lend

}

//Service 服务的开启监听和停止，优雅的退出
func Service() error {
	newSvr := new(http.Server)
	newSvr.Handler = http.DefaultServeMux
	newSvr.Addr = fmt.Sprintf(":%d", port)
	httpSrvs = append(httpSrvs, newSvr)
	go func() {
		//这种连接是有证书的情况下，连接方式使用https，ListenAndServeTLS参数是两个文件的路径
		// if strings.ToLower(schema) == "https" {
		// 	if err := newSvr.ListenAndServeTLS(core.DataFile("server.crt"), core.DataFile("server.key")); err != nil {
		// 		core.LOG.Fatal(err)
		// 	}
		// }

		if err := newSvr.ListenAndServe(); err != nil {
			log.Println(err)
		}

	}()
	return nil
}

//Shutdown 停止http服务
func Shutdown() {
	for _, one := range httpSrvs {
		if err := one.Shutdown(context.Background()); err != nil {
			log.Println(err)
		}
	}
}
